#!/usr/bin/perl -w

use strict;
use Cwd;
use File::Basename;
use File::Find;
use Getopt::Long qw(:config pass_through);

my $build = 0;
my $rootDir = getcwd;
my $buildDir = $rootDir."/build/";
my $clean = 0;
my $debugMode = 0;
my $releaseMode = 1;
my $showHelp = 0;
my $thirdPartyDir = $rootDir."/third_party/";
my $webkitBuild = 0;
my $webkitDependency = 0;
my $webkitUpdate = 0;
my $webkitDir = $thirdPartyDir."WebKit";
my $webkitGitUrl = "git://git.webkit.org/WebKit.git";

# Initialize values from arguments
my %options = (
    'help' => \$showHelp,
    'clean' => \$clean,
    'webkit-update' => \$webkitUpdate,
    'webkit-build' => \$webkitBuild,
    'webkit-install-dependencies' => \$webkitDependency,
	'debug' => \$debugMode,
	'release' => \$releaseMode,
	'build' => \$build,
);

if (@ARGV < 1) {
	ShowHelpMessage();
	exit 1;
}

GetOptions(%options);

if ($showHelp) {
	ShowHelpMessage();
	exit 1;
}

if ($webkitUpdate) {
    UpdateWebKit();	
}

if ($webkitDependency) {
    InstallWebKitPackages();	
}

if ($webkitBuild) {
	BuildWebKit();
}

# check webkit source
sub CheckWebKitSource {
	my $gitConfigFile = $webkitDir."/.git/config";
	
	die "Error: Webkit source does not exist. \nPlease run this command :\n\ttools/build --update-webkit\n\n" if (! -e $gitConfigFile);
}

# install webkit package 
sub InstallWebKitPackages {
	CheckWebKitSource();
	
	if (! -d $buildDir) {
		mkdir($buildDir); 
		symlink($buildDir, "$webkitDir/WebKitBuild");
	}

	chdir($webkitDir);
	(system("Tools/efl/install-dependencies") == 0) or die "Error: Packages download error\n\n";
	(system("Tools/Scripts/update-webkitefl-libs") == 0) or die "Error: Packages download error\n\n";
	chdir($rootDir);
}

# build webkit
sub BuildWebKit {
	chdir($webkitDir);
	(system("Tools/Scripts/build-webkit", "--efl", "--no-webkit2", "--only-webkit") == 0) or die "Error: webkit build error\n\n";
	chdir($rootDir);
}

# update webkit source
sub UpdateWebKit {
	my $gitConfigFile = $webkitDir."/.git/config";
	
	chdir($thirdPartyDir);
	if (-e $gitConfigFile) {
    	(system("git", "pull") == 0) or die "Error: Please install git\n\n";
	}
	else {
    	(system("git", "clone", $webkitGitUrl, "WebKit") == 0) or die "Error: Please install git\n\n";
	}
	chdir($rootDir);
}

# help message
sub ShowHelpMessage {
	my $programName = basename($0);
	my $usage = <<EOF;
Usage: $programName [options]
    --help                  Show this help message
    --clean                 Cleanup the build directory
    --debug                 Compile with Debug configuration
    --release               Compile with Release configuration
    --webkit-update         Update the webkit source from repositary of WebKit
    --webkit-build          Build WebKit
    --webkit-dependencies   Install dependency packages of WebKit
    --build                 Build EFl Browser

EOF
    print $usage; 
};

